<?php
/**
 * Created by PhpStorm.
 * User: jiangtaiping
 * Date: 2017/2/23
 * Time: 11:39
 */
class Service_ManagerMall{

    /**
     * 获取后台账号信息
     * @param int $uid 指定的账号ID
     * @return array
     */
    public static function getInfoById($uid=0)
    {
        if($uid == 0){
            return array();
        }
        $cacheKey = "manager-info-" . $uid;
        $cacheValue = FCache::get($cacheKey);
        if ($cacheValue){
            return $cacheValue;
        }
        $managerTable = new FTable('manager', '', 'xhs_slave');
        $managerData = $managerTable->where(array('uid' => $uid))->find();
        FCache::set($cacheKey, $managerData,86400);
        return $managerData;
    }

    public static function clearInfoById($uid=0){
        $cacheKey = "manager-info-" . $uid;
        FCache::delete($cacheKey);
        self::getInfoById($uid);
    }
    /**
     * 获取当前用户的信息和状态
     * @return array|bool
     */
    public static function getSessionData()
    {
        global $_F;
        $auth_str = FCookie::get('manager_auth');
        list($uid, $auth) = explode("\t", $auth_str);

        if (!$auth) {
            return false;
        }

        $check_auth = null;
        $managerTable = new FTable('manager', '', 'xhs_slave');

        $managerData = $managerTable->where(array('uid' => $uid))->find();
        if ($managerData) {
            $check_auth = md5("{$managerData['username']}|{$managerData['password']}|{$managerData['groupid']}");
        }

        if ($check_auth == $auth) {
            $_F['member'] = $managerData;
            $_F['uid'] = $uid;
            $_F['gid'] = $managerData['groupid'];
            return $managerData;
        }
        FCookie::set('manager_auth', '', -1);
        return false;
    }

    /**
     * 移除当前账号的认证cookie
     */
    public static function removeSession()
    {
        FCookie::set('manager_auth', '', -1);
    }

    /**
     * 检测是否有权限访问一个地址
     * @param string $url 要访问的方法，为空时自动获取当前的方法
     * @return bool
     */
    public static function checkRole($url = '',$gid=0){
        global $_F;
        if($gid == 0){
            $gid = $_F['gid'];
        }
        /**
         * 如果当前组是超级管理员组，直接全部通过
         */
        if($gid == FConfig::get('global.super_gid')){
            return true;
        }
        if($url == ''){
            $url = strtolower('/'.$_F['module'].'/'.str_replace('controller_'.$_F['module'].'_','',strtolower($_F['controller'])).'/'.$_F['action']);
        }
        $groupRole = self::getGroupRole($gid);
        if(in_array($url,$groupRole)){
            return true;
        }
        return false;
    }

    /**
     * 获取用户组的权限配置
     * @param int $gid 用户组ID
     * @return array
     */
    public static function getGroupRole($gid){
        $cache_key = 'adminmall_group_cache_'.$gid;
        $Role = FCache::get($cache_key);
        if(!$Role){
            $groupTable = new FTable('manager_group', '', 'xhs_slave');
            $roleData = $groupTable->fields('permission')->where(array('id'=>$gid))->find();
            if($roleData){
                $Role = unserialize($roleData['permission']);
            }else{
                $Role = array();
            }
            /**
             * 开发时给所有的权限
             * $permission = FConfig::get('permission');
             * $Role = array_keys($permission);
             */
            /**
             * 补充基本拥有的界面权限
             */
            $basic = FConfig::get('permission.basic_xhs');
            $Role = array_merge($Role,$basic);
            FCache::set($cache_key,$Role,30*86400);
        }
        return $Role;
    }

    /**
     * 更新用户组权限缓存
     * @param int $gid 组id
     */
    public static function clearGroupRole($gid){
        $cache_key = 'adminmall_group_cache_'.$gid;
        FCache::delete($cache_key);
        self::getGroupRole($gid);
    }

    /**
     * 获取加密后的密码
     * @param string $password 密码
     * @return string
     */
    public static function getEncryptPassword($password)
    {
        return md5($password);
    }

    /**
     * 写入一条后台操作日志
     * @param string $action 日志事件
     * @param string $comment 事件详细描述
     * @param int $mid 管理员ID
     * @return bool
     */
    public static function addManagerLog($action='',$comment='',$mid=0){
        global $_F;
        if($action == "" && $comment == "") return false;
        if($mid == 0){
            $mid = isset($_F['uid']) ? $_F['uid'] : 0;
        }
        $logTable = new FTable('manager_log', '', 'xhs_master');
        $logTable->insert(array(
            'action'=>$action,
            'comment'=>$comment,
            'mid'=>$mid,
            'create_time'=>date('Y-m-d H:i:s'),
            'ip'=>FRequest::getClientIP()
        ));
        return true;
    }

    /**
     * 更新运营、代理的下属体验师统计数
     * 体验师注册注销时
     * @param int $uid 代理 ID
     * @return bool
     */
    public static function setExperTotal($uid){
        $userTable = new FTable('user', '', 'xhs_slave');
        $proxy=$userTable->where(array('account_type'=>2,'uid'=>$uid))->find();
        if(!$proxy){
            return false;
        }
        $proxytysnum=$userTable->where(array('account_type'=>1,'proxy_id'=>$uid))->count();
        $userTable->update1(array('exper_total'=>$proxytysnum),array('uid'=>$uid));
        if($proxy['mid']){
            $mtysnum=$userTable->where(array('account_type'=>1,'mid'=>$proxy['mid']))->count();
//            $mproxynum=$userTable->where(array('account_type'=>2,'mid'=>$proxy['mid']))->count();
            $managerTable = new FTable('manager', '', 'xhs_master');
            $managerTable->where(array('uid'=>$proxy['mid']))
                ->update1(array(
                    'exper_total'=>$mtysnum,
//                    'proxy_total'=>$mproxynum
                ));
        }
        return true;
    }
    /**
     * 更新运营下属代理统计数
     * 代理注册注销时
     * @param int $uid 代理 ID
     * @return bool
     */
    public static function setProxyTotal($mid){
        $userTable = new FTable('user', '', 'xhs_slave');
        $mtysnum=$userTable->where(array('account_type'=>1,'mid'=>$mid))->count();
        $mproxynum=$userTable->where(array('account_type'=>2,'mid'=>$mid))->count();
        $managerTable = new FTable('manager', '', 'xhs_master');
        $managerTable->where(array('uid'=>$mid))
            ->update1(array(
                'exper_total'=>$mtysnum,
                'proxy_total'=>$mproxynum
            ));

        return true;
    }
}
